<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>大文件上传</span>
      </div>
      
      <el-upload 
        ref="upload" 
        action="/upload" 
        :auto-upload="true" 
        :on-success="handleSuccess" 
        :on-error="handleError"
        :before-upload="beforeUpload" 
        :http-request="customUpload" 
        :file-list="fileList" 
        :limit="1"
        :on-progress="handleProgress"
        :on-remove="handleRemove"
      >
        <el-button slot="trigger" type="primary" :disabled="fileList.length >= 1">
          选择文件
        </el-button>
        <div slot="tip" class="el-upload__tip">支持上传大文件，单个文件不超过1500000MB</div>
      </el-upload>

      <!-- 进度条 -->
      <el-progress 
        v-if="uploadProgress" 
        :percentage="uploadProgress" 
        :status="uploadStatus"
        style="margin-top: 20px;" 
      />

      <!-- 文件列表和操作按钮 -->
      <div v-if="fileList.length > 0" class="file-list-container" style="margin-top: 20px;">
        <el-table :data="fileList" style="width: 100%">
          <el-table-column prop="name" label="文件名称" />
          <el-table-column prop="size" label="文件大小" width="180">
            <template slot-scope="scope">
              {{ formatFileSize(scope.row.size) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 'success' ? 'success' : 'warning'">
                {{ scope.row.status === 'success' ? '已上传' : '上传中' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <el-button
                type="danger"
                size="mini"
                @click="handleDelete(scope.row)"
                :disabled="uploadProgress > 0"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="operation-container" style="margin-top: 20px; text-align: center;">
          <el-button 
            type="primary" 
            :disabled="!canProcess || isProcessing" 
            @click="handleProcess"
          >
            {{ isProcessing ? '处理中...' : '开始处理文档' }}
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';
import { uploadApi } from '@/api/upload'

export default {
  data() {
    return {
      fileList: [], // 存储上传的文件列表
      uploadProgress: 0, // 上传进度
      chunkSize: 1024 * 1024 * 0.8, // 每次上传的文件块大小，0.8MB
      uploadStatus: '', // 上传状态
      isProcessing: false, // 是否正在处理文档
      currentFile: null, // 当前正在上传的文件信息
      uploadingMessage: null // 用于存储上传中的消息实例
    };
  },
  computed: {
    canProcess() {
      return this.fileList.length > 0 && this.fileList.every(file => file.status === 'success');
    }
  },
  methods: {
    formatFileSize(size) {
      if (size < 1024) {
        return size + ' B';
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + ' KB';
      } else if (size < 1024 * 1024 * 1024) {
        return (size / (1024 * 1024)).toFixed(2) + ' MB';
      } else {
        return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
      }
    },

    beforeUpload(file) {
      const maxSize = 1024 * 1024 * 1500000;  // 设置最大文件大小（1500000MB）
      if (file.size > maxSize) {
        this.$message.error('文件大小不能超过 1500000MB');
        return false;
      }
      this.currentFile = {
        name: file.name,
        size: file.size,
        status: 'uploading'
      };
      return true;
    },

    handleProgress(event, file, fileList) {
      this.uploadProgress = Math.round((event.loaded / event.total) * 100);
      this.uploadStatus = this.uploadProgress === 100 ? 'success' : '';
    },

    handleSuccess(response, file, fileList) {
      this.$message.success('文件上传成功');
      this.uploadProgress = 0;
      this.uploadStatus = 'success';
      if (this.currentFile) {
        this.currentFile.status = 'success';
        this.fileList = [this.currentFile];
      }
    },

    handleError(error, file, fileList) {
      this.$message.error('文件上传失败');
      this.uploadProgress = 0;
      this.uploadStatus = 'exception';
      if (this.currentFile) {
        this.currentFile.status = 'error';
      }
    },

    handleDelete(file) {
      this.$confirm('确认删除该文件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 这里可以调用删除文件的API
        this.fileList = this.fileList.filter(item => item !== file);
        this.$message.success('删除成功');
      }).catch(() => {});
    },

    handleRemove(file, fileList) {
      this.fileList = fileList;
    },

    handleProcess() {
      if (!this.canProcess) return;
      
      this.isProcessing = true;
      // 这里添加处理文档的API调用
      setTimeout(() => {
        this.$message.success('文档处理完成');
        this.isProcessing = false;
      }, 2000);
    },

    customUpload(options) {
      const file = options.file;
      const totalChunks = Math.ceil(file.size / this.chunkSize);
      var chunkFile = 0;

      // 显示上传中的消息
      this.uploadingMessage = this.$message({
        message: '文件上传中...',
        duration: 0,
        type: 'info'
      });

      const uploadChunk = async (chunkIndex) => {
        const start = chunkIndex * this.chunkSize;
        const end = Math.min(start + this.chunkSize, file.size);
        const blob = file.slice(start, end);

        console.log(`Blob size: ${blob.size} bytes`);

        const formData = new FormData();
        formData.append('file', blob);
        formData.append('filename', file.name);
        formData.append('chunk', chunkIndex);
        formData.append('totalChunks', totalChunks);

        try {
          const res = await uploadApi(formData, {
            onUploadProgress: (progressEvent) => {
              chunkFile = progressEvent.total + chunkFile;
              this.uploadProgress = Math.round((chunkFile / file.size) * 100);
            }
          });

          // 不处理每个分片的成功消息
          console.log(`Chunk ${chunkIndex + 1}/${totalChunks} uploaded`);

          if (chunkIndex + 1 < totalChunks) {
            await uploadChunk(chunkIndex + 1);  // 递归上传下一个块
          } else {
            // 所有分片上传完成后，关闭上传中消息，显示上传成功
            if (this.uploadingMessage) {
              this.uploadingMessage.close();
            }
            this.$message.success('文件上传完成');
            this.uploadProgress = 0;
            if (this.currentFile) {
              this.currentFile.status = 'success';
              this.fileList = [this.currentFile];
            }
          }
        } catch (error) {
          // 发生错误时，关闭上传中消息，显示错误信息
          if (this.uploadingMessage) {
            this.uploadingMessage.close();
          }
          this.$message.error('上传失败');
          if (this.currentFile) {
            this.currentFile.status = 'error';
          }
          throw error; // 向上传递错误
        }
      };

      uploadChunk(0).catch(err => {
        // 发生错误时，确保关闭上传中消息
        if (this.uploadingMessage) {
          this.uploadingMessage.close();
        }
        console.error(err);
      });
    },
  },
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  min-height: calc(100vh - 84px);
  background-color: #f0f2f5;
}
.box-card {
  margin-bottom: 20px;
  min-height: calc(100vh - 124px);
  display: flex;
  flex-direction: column;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.file-list-container {
  margin-top: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
}
.operation-container {
  margin-top: 20px;
  padding: 20px 0;
  border-top: 1px solid #EBEEF5;
}
.el-upload__tip {
  color: #909399;
  margin-top: 10px;
}
.el-table {
  flex: 1;
}
</style>